package com.sgb.member.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityAddMemberDoorBinding;
import com.sgb.member.entity.ParamBean;
import com.sgb.member.view_model.AddMemberDoorModel;
import com.sgb.member.weight.MemberTypeDialog;
import com.sgb.member.weight.SimpleResult;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.List;

/**
 * 新增会员门槛
 */
public class AddMemberDoorActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private AddMemberDoorModel viewModel;
    ActivityAddMemberDoorBinding mBinding;
    private List<ParamBean> viewList = new ArrayList<>();//自定义参数

    private OptionsPickerView<CommonPopEntity> mOption5, mOption;
    private List<CommonPopEntity> mPop = new ArrayList<>();
    private List<CommonPopEntity> mPop5 = new ArrayList<>();
    private String type = "";
    private String typeOri = "";
    public String firstCategory;
    public String secondCategory;
    public String thirdCategory;
    public String typeName = "";

    public static void start(Context context) {
        Intent intent = new Intent(context, AddMemberDoorActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String relation, String firstCategory, String secondCategory, String thirdCategory, String typeName) {
        Intent intent = new Intent(context, AddMemberDoorActivity.class);
        intent.putExtra("relation", relation);
        intent.putExtra("firstCategory", firstCategory);
        intent.putExtra("secondCategory", secondCategory);
        intent.putExtra("thirdCategory", thirdCategory);
        intent.putExtra("typeName", typeName);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        viewModel = new ViewModelProvider(this).get(AddMemberDoorModel.class);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_member_door);
        type = getIntent().getStringExtra("relation");
        firstCategory = getIntent().getStringExtra("firstCategory");
        secondCategory = getIntent().getStringExtra("secondCategory");
        thirdCategory = getIntent().getStringExtra("thirdCategory");
        typeName = getIntent().getStringExtra("typeName");
        if (TextUtils.isEmpty(typeName)) {
            mBinding.activityBar.titleView.setText("新增会员门槛");
        } else {
            mBinding.activityBar.titleView.setText("编辑会员门槛");
            mBinding.itvType.setContent(typeName);
        }
        mBinding.activityBar.ivBack.setOnClickListener(v -> finish());
        mBinding.tvAddView.setOnClickListener(v -> addView());
        mBinding.tvDelView.setOnClickListener(v -> delView());
        mBinding.itvApply.setOnWholeItemClickListener(this);
        mBinding.itvType.setOnWholeItemClickListener(this);
        mBinding.itvFile.setOnWholeItemClickListener(this);
        mBinding.tvSubmit.setOnClickListener(v -> submitData());
        mPop.add(new CommonPopEntity("1", "是"));
        mPop.add(new CommonPopEntity("2", "否"));
        mPop5.add(new CommonPopEntity("1", "供方会员"));
        mPop5.add(new CommonPopEntity("2", "需方会员"));

        receiverLiveData();
        showDetail();
    }

    private void showDetail() {
        if (!TextUtils.isEmpty(typeName)) {
            viewModel.getThreshold(type, firstCategory, secondCategory, thirdCategory);
        }
    }

    private void receiverLiveData() {
        viewModel.msgLiveData.observe(this, s -> {
            MToast.showToast(this, s);
        });
        viewModel.isLoadLiveData.observe(this, b -> {
            if (b) {
                DialogHelper.showProgressDialog(this, "正在上传");
            } else {
                DialogHelper.dismissProgressDialog();
            }
        });
        viewModel.memberTypes.observe(this, commonPopEntities -> {
            if (commonPopEntities != null) {
                showMemberTypePopup2(commonPopEntities);
            }
        });

        viewModel.detailLiveData.observe(this, data -> {
            mBinding.leaseDes.setEditContent("");
            mBinding.itvFile.setContent("");
            viewList.clear();
            mBinding.llDescGroup.removeAllViews();

            if (data.size() > 0) {
                String relation = data.get(0).getRelation();
                type = relation;
                if (relation.equals("1")) {
                    mBinding.itvApply.setContent("供方会员");
                } else {
                    mBinding.itvApply.setContent("需方会员");
                }

                for (int i = 0; i < data.size(); i++) {
                    if (i == 0) {
                        mBinding.leaseDes.setEditContent(data.get(0).getRequiredContent());
                        mBinding.itvFile.setContent(TextUtils.equals(data.get(0).isSupportDoc(), "1") ? "是" : "否");
                    } else {
                        View view = View.inflate(getActivity(), R.layout.layout_member_new_add_item, null);
                        ((CfkEditView) view.findViewById(R.id.tv_desc_content)).setEditContent(data.get(i).getRequiredContent());
                        ItemInputTextView itvFile = view.findViewById(R.id.itv_file);
                        itvFile.setContent(TextUtils.equals(data.get(i).isSupportDoc(), "1") ? "是" : "否");
                        mBinding.llDescGroup.addView(view, mBinding.llDescGroup.getChildCount());
                        itvFile.setOnWholeItemClickListener(v -> {
                            showIsNeedFilePop2((entity, objects) -> {
                                itvFile.setContent(entity.getTypeName());
                            });
                        });
                        TextView tvDel = view.findViewById(R.id.tv_del);
                        tvDel.setOnClickListener(view1 -> mBinding.llDescGroup.removeView(view));
                        if (mBinding.llDescGroup.getChildCount() >= 4) {
                            mBinding.tvAddView.setVisibility(View.GONE);
                        }
                        mBinding.tvDelView.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
        viewModel.isSuccessLiveData.observe(this, data -> {
            MToast.showToast(this, "保存成功！");
            finish();
        });
    }



    private MemberTypeDialog dialogFragment;
    private boolean isShowDialog = false;
    private void showMemberTypePopup2(List<CommonPopEntity> data) {
        if(!isShowDialog){
            isShowDialog =true;
            dialogFragment = new MemberTypeDialog(this, data, firstCategory, secondCategory, thirdCategory);
            dialogFragment.setCancelable(false);
            dialogFragment.setDialogDialogCallback(new MemberTypeDialog.DialogCallback() {
                @Override
                public void back(String no1, String no2, String no3, String name) {
                    isShowDialog = false;
                    firstCategory = no1;
                    secondCategory = no2;
                    thirdCategory = no3;
                    mBinding.itvType.setContent(name);
                    viewModel.getThreshold(type, firstCategory, secondCategory, thirdCategory);
                }

                @Override
                public void dissDiag() {
                    isShowDialog = false;
                   dialogFragment.dismiss();
                }
            });
            dialogFragment.show(getSupportFragmentManager(), "dialog");
        }
    }

    private void submitData() {
        String itv_apply = mBinding.itvApply.getContent();
        if (TextUtils.isEmpty(itv_apply)) {
            MToast.showToast(this, "请选择供需关系");
            return;
        }
        String itv_type = mBinding.itvType.getContent();
        if (TextUtils.isEmpty(itv_type)) {
            MToast.showToast(this, "请选择会员类型");
            return;
        }
        String tv_desc_content = mBinding.leaseDes.getEditContent();
        if (TextUtils.isEmpty(tv_desc_content)) {
            MToast.showToast(this, "请输入要求内容");
            return;
        }
        String itv_file = mBinding.itvFile.getContent();
        if (TextUtils.isEmpty(itv_file)) {
            MToast.showToast(this, "请选择是否需要证明文件");
            return;
        }
        if (!getViewList()) {
            return;
        }
        viewModel.submitData(type, firstCategory, secondCategory, thirdCategory, viewList);
    }

    private void addView() {
        if (TextUtils.isEmpty(mBinding.leaseDes.getEditContent().trim())) {
            MToast.showToast(getActivity(), "请输入要求内容");
            return;
        }
        if (TextUtils.isEmpty(mBinding.itvFile.getContent())) {
            MToast.showToast(getActivity(), "请选择是否需要证明文件");
            return;
        }
        if (mBinding.llDescGroup.getChildCount() >= 4) {
            MToast.showToast(getActivity(), "最多设置5个要求");
            return;
        }
        if (!getViewList2()) {
            return;
        }
        View view = View.inflate(getActivity(), R.layout.layout_member_new_add_item, null);
        mBinding.llDescGroup.addView(view, mBinding.llDescGroup.getChildCount());
        ItemInputTextView itv_file = view.findViewById(R.id.itv_file);
        itv_file.setOnWholeItemClickListener(v -> {
            showIsNeedFilePop2((entity, objects) -> {
                itv_file.setContent(entity.getTypeName());
            });
        });

        TextView tvDel = view.findViewById(R.id.tv_del);
        tvDel.setOnClickListener(view1 -> mBinding.llDescGroup.removeView(view));
        if (mBinding.llDescGroup.getChildCount() > 1) {
            View itemView = mBinding.llDescGroup.getChildAt(mBinding.llDescGroup.getChildCount() - 2);
            itemView.findViewById(R.id.tv_del).setVisibility(View.VISIBLE);
        }
        if (mBinding.llDescGroup.getChildCount() >= 4) {
            mBinding.tvAddView.setVisibility(View.GONE);
        }
        mBinding.tvDelView.setVisibility(View.VISIBLE);
    }

    private void delView() {
        int n = mBinding.llDescGroup.getChildCount();
        if (n > 0) {
            mBinding.llDescGroup.removeViewAt(n - 1);
            if (mBinding.llDescGroup.getChildCount() == 0) {
                mBinding.tvDelView.setVisibility(View.GONE);
                mBinding.tvAddView.setVisibility(View.VISIBLE);
            } else {
                View itemView = mBinding.llDescGroup.getChildAt(mBinding.llDescGroup.getChildCount() - 1);
                itemView.findViewById(R.id.tv_del).setVisibility(View.GONE);
                if (mBinding.llDescGroup.getChildCount() < 4) {
                    mBinding.tvAddView.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    public boolean getViewList() {
        viewList.clear();
        String desc_content = mBinding.leaseDes.getEditContent();
        String isfile = mBinding.itvFile.getContent();
        ParamBean bean1 = new ParamBean();
        bean1.setContent(desc_content);
        bean1.setNeedFile(isfile.equals("是") ? "1" : "2");
        viewList.add(bean1);
        for (int i = 0; i < mBinding.llDescGroup.getChildCount(); i++) {
            View view = mBinding.llDescGroup.getChildAt(i);
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请填写要求内容");
                return false;
            }
            String itv_file = ((ItemInputTextView) view.findViewById(R.id.itv_file)).getContent().trim();
            if (TextUtils.isEmpty(itv_file)) {
                MToast.showToast(getActivity(), "请选择是否需要证明文件");
                return false;
            }
            ParamBean bean = new ParamBean();
            bean.setContent(content);
            bean.setNeedFile(itv_file.equals("是") ? "1" : "2");
            viewList.add(bean);
        }
        return true;
    }

    public boolean getViewList2() {
        for (int i = 0; i < mBinding.llDescGroup.getChildCount(); i++) {
            View view = mBinding.llDescGroup.getChildAt(i);
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请填写要求内容");
                return false;
            }
            String itv_file = ((ItemInputTextView) view.findViewById(R.id.itv_file)).getContent().trim();
            if (TextUtils.isEmpty(itv_file)) {
                MToast.showToast(getActivity(), "请选择是否需要证明文件");
                return false;
            }
        }
        return true;
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.itv_apply) {
            showSupplyDemandPop();
        } else if (id == R.id.itv_type) {
            // ascription 0 供方 1需方
            if (TextUtils.isEmpty(type)) {
                MToast.showToast(this, "请选择供需关系");
                return;
            }
            if (!TextUtils.equals(typeOri, type)) {
                typeOri = type;
                viewModel.memberTypes.setValue(null);
            }
            if (viewModel.memberTypes.getValue() == null) {
                viewModel.getMemberTypeList(type);
            } else {
                showMemberTypePopup2(viewModel.memberTypes.getValue());

            }
        } else if (id == R.id.itv_file) {
            showIsNeedFilePop();
        }
    }

    private void showIsNeedFilePop() {
        if (mOption == null) {
            mOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
//                String no = mPop.get(options1).getNo();
                String name = mPop.get(options1).getTypeName();
                mBinding.itvFile.setContent(name);
            }).setCancelColor(this.getResources().getColor(R.color.color_title_small))
                    .setLineSpacingMultiplier(2.2f)
                    .setCancelColor(0xFF666666)
                    .setTitleColor(0xFF969696)
                    .setSubCalSize(15)
                    .setTitleSize(15)
                    .setContentTextSize(15)
                    .build();
            mOption.setTitleText("是否需要证明文件");
            mOption.setPicker(mPop);
        }
        mOption.setSelectOptions(0);
        mOption.show();
    }

    private void showIsNeedFilePop2(SimpleResult<CommonPopEntity> simpleResult) {
        OptionsPickerView<CommonPopEntity> mOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            simpleResult.onResult(mPop.get(options1));
        }).setCancelColor(this.getResources().getColor(R.color.color_title_small))
                .setLineSpacingMultiplier(2.2f)
                .setCancelColor(0xFF666666)
                .setTitleColor(0xFF969696)
                .setSubCalSize(15)
                .setTitleSize(15)
                .setContentTextSize(15)
                .build();
        mOption.setTitleText("是否需要证明文件");
        mOption.setPicker(mPop);
        mOption.setSelectOptions(0);
        mOption.show();
    }


    /**
     * 供需关系 1:供方2:需方
     */
    public void showSupplyDemandPop() {
        if (mOption5 == null) {
            mOption5 = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String no = mPop5.get(options1).getNo();
                String name = mPop5.get(options1).getTypeName();
                type = no;
                mBinding.itvApply.setContent(name);
                mBinding.itvType.setContent("");
            }).setCancelColor(this.getResources().getColor(R.color.color_title_small))
                    .setLineSpacingMultiplier(2.2f)
                    .setCancelColor(0xFF666666)
                    .setTitleColor(0xFF969696)
                    .setSubCalSize(15)
                    .setTitleSize(15)
                    .setContentTextSize(15)
                    .build();
            mOption5.setTitleText("供需关系");
            mOption5.setPicker(mPop5);
        }
        mOption5.setSelectOptions(0);
        mOption5.show();
    }


}
